import Vue from 'vue'
import store from '@/store'
import Router from 'vue-router'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Message } from 'element-ui'

//去除重复跳转报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)
var arr = []

// 获取 pages 下面那些 router
const r = require.context("../pages",true,/\.js$/)
r.keys().forEach(item => {
  item = r(item)
  arr = arr.concat(item.default)
})
const routes = [
  {
    path: '/',
    redirect: '/Home'
  },
  ...arr
]

const router = new Router({
  mode: 'hash',
  routes
})


// 把路径还有名字放进Worktab 这个是标签导航栏用到的

// 路由导航守卫
const notoken = ['/login','/forgetPassword','/register','/index','/list'] // 不需要tonken的页面
router.beforeEach((to, from, next) => {
  // NProgress.start();
  if(notoken.indexOf(to.path) == -1) {
    const token = sessionStorage.getItem('token')
    if(token == null || token == '') {
      Message.info('您不在登录状态，请先登录!')
      router.replace('/login')
    }
  }
  store.dispatch('worktabRoute',{
    to: {
      name: to.meta.title,
      path: to.fullPath
    },
    from: {
      name: from.meta.title,
      path: from.fullPath
    }
  })
  next()
})

export default router

